package handlers

import (
	"2-11zy/api/request"
	"2-11zy/api/response"
	"2-11zy/dao"
	"2-11zy/models"
	"2-11zy/pkg"
	"github.com/gin-gonic/gin"
	jwt "github.com/golangblogs/gojwt"
	"path"
)

func Upload(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		response.ResponseError(c, "文件上传错误")
		return
	}
	ext := path.Ext(file.Filename)
	end := map[string]bool{
		".png": true,
		".jpg": true,
		".mp4": true,
	}
	if !end[ext] {
		response.ResponseError(c, "文件类型错误")
		return
	}
	if file.Size >= 500*1024*1024 {
		response.ResponseError(c, "文件过大")
		return
	}
	dst := "C:\\Users\\86199\\Desktop\\2.11zy\\static\\upload" + file.Filename
	c.SaveUploadedFile(file, dst)

	pkg.Upload(dst, file.Filename)
	response.ResponseSuccess(c, pkg.TaRul(file.Filename))
}

func Login(c *gin.Context) {
	var data request.Login
	err := c.ShouldBind(&data)
	if err != nil {
		response.ResponseError(c, err.Error())
		return
	}
	user, err := dao.GetUser(data.Phone)
	if err != nil {
		response.ResponseError(c, "查询失败")
		return
	}
	if user.Phone == "" {
		m := models.User{
			Phone:    data.Phone,
			Password: data.Password,
		}
		err := dao.UserCreate(m)
		if err != nil {
			response.ResponseError(c, "注册失败")
			return
		}
	}
	if data.Password != user.Password {
		response.ResponseError(c, "密码错误")
		return
	}
	claims := jwt.CustomClaims{ID: user.ID}
	token, err := jwt.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		response.ResponseError(c, "token生成失败")
		return
	}
	response.ResponseSuccess(c, token)
}
